#include "Score.h"

void scoreInit(Score score)
{
    score = 0;
}

void afficheScore(Score score)
{
    printf("Distance : %d",score);
}

void triParSelectionDuMinimum(int * tab, int taille)
{
	int i, j, indice;
	int min;
	for (i=0; i<taille-1; i++)
	{
		indice = i;
		for( j=(i+1); j<taille; j++)
		{
			if(tab[j] < tab[indice])
			{
				indice = j;
			}
		}
		min = tab[indice];
		tab[indice] = tab[i];
		tab[i] = min;
	}
}


void enregScore(const Score score, const char nomfichier[])
{
    int i=0;
    int * tabscore;
    tabscore=(int*)malloc(10*sizeof(int));
    FILE * scoreFic;
    scoreFic = fopen(nomfichier, "r");
    if (scoreFic==NULL)
    {
        printf("Erreur lors de l'ouverture de %s\n", nomfichier);
        assert(scoreFic);
    }

   for(i=0;i<10;i++)
    {
        fscanf (scoreFic, "%d", &tabscore[i]);
    }

    fclose(scoreFic);

    tabscore[0]=score;

    triParSelectionDuMinimum(tabscore, 10);

    scoreFic=fopen(nomfichier, "w");
    if (scoreFic==NULL)
    {
        printf("Erreur lors de l'ouverture de %s\n", nomfichier);
        assert(scoreFic);
    }

    for(i=0;i<10;i++)
    {
        fprintf(scoreFic, "%d ", tabscore[i]);
    }
    fclose(scoreFic);
    free(tabscore);
}


void verifScore(const Score score, const char nomfichier[])
{
    int s10,testscan;
    FILE * scoreFic;
    scoreFic = fopen(nomfichier, "r");
    if (scoreFic==NULL)
    {
        printf("Erreur lors de l'ouverture de %s\n", nomfichier);
        assert(scoreFic);
    }

    testscan = fscanf (scoreFic, "%d", &s10);

	if(testscan == 1)
	{
        if(s10<(score))
        {
            enregScore(score, nomfichier);
        }
	}
	fclose(scoreFic);
}
